<?php

namespace app\manystore\controller\Pay;

use think\Db;
use app\common\controller\ManystoreBase;
use app\manystore\Logic\Pay\PayLogic;
use app\manystore\model\PayLog;
use app\manystore\Model\AddService;
use app\manystore\Model\ManystoreOrderRecord;
use app\manystore\Model\ManystoreConfig;
use app\manystore\Model\ManystoreShop;

/**
 * 支付接口
 */
class Pay extends ManystoreBase
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';
    protected $payLogic;

    public function _initialize()
    {
        parent::_initialize();
        $this->payLogic = new PayLogic();
    }

    /**
     * 获取支付方式
     *
     * @ApiMethod (GET)
     * @ApiTitle    获取支付方式

     * @ApiSector   我的接口
     * @ApiReturn   ({
          "code": 1,
          "msg": "获取数据成功",
          "time": "1657984618",
          "data": null
        })
     */
    public function payTypeAry(){
        $list = array_values($this->payLogic->payTypeMap());
        if (!empty($list)) {
            $this->success('查询成功','', $list);
        }
        $this->error('暂无数据');
    }

    /**
     * 创建订单并返回支付回调信息
     *
     * @ApiMethod (GET)
     * @ApiTitle    获取增值服务

     *  @ApiParams (name="pay_good_type", type="integer", required=false, description="类型:1=增值服务")
     *  @ApiParams (name="good_id", type="integer", required=false, description="商品ID")
     *  @ApiParams (name="number", type="integer", required=false, description="购买数量")
     *  @ApiParams (name="pay_type", type="integer", required=false, description="付款方式:1=微信支付,2=支付宝支付,3=银联支付")

     * @ApiSector   我的接口
     * @ApiReturn   ({
          "code": 1,
          "msg": "获取数据成功",
          "time": "1657984618",
          "data": null
        })
     */
    public function createOrder()
    {
        $user = $this->auth->getUserinfo();

        if(empty($user['shop_id']))
        {
            $this->error('非商家无权限');
        }

        $store_info = ManystoreShop::get($user['shop_id']);
        if(empty($store_info))
        {
            $this->error('非商家无权限');
        }

        $param = $this->request->param();

        if(empty($param['good_id']))
        {
            $this->error('请选择要购买的商品');
        }

        if(empty($param['number']) || $param['number'] <= 0)
        {
            $this->error('购买数量错误');
        }

        if(!isset($param['pay_type']) || !isset($this->payLogic->payTypeMap()[$param['pay_type']]))
        {
            $this->error('支付方式不可用');
        }

        //购买增值服务
        if($param['pay_good_type'] == 1)
        {
            $goodInfo = AddService::where(['id' => $param['good_id'],'status' => 1])->find();
            if(empty($goodInfo))
            {
                $this->error('商品已下架');
            }

            Db::startTrans();
            try {
                $star_time = 0;
                $end_time = 0;
                if($goodInfo['type'] == 1 && $goodInfo['num'] > 0)
                {
                    $sys_extend_day = intval(ManystoreConfig::where('name','sys_extend_day')->value('content'));
                    $add_time = bcmul($goodInfo['num'],86400);

                    $star_time = empty($store_info['end_time']) ? time() : ($store_info['end_time'] > time() ? $store_info['end_time'] : time());
                    $end_time = bcadd($add_time,($store_info['end_time'] > time() ? $store_info['end_time'] : time()));
                }

                //添加服务商订购记录
                $orderInfo = [
                    'shop_id' => $user['shop_id'],
                    'add_service_id' => $goodInfo['id'],
                    'type' => $goodInfo['type'],
                    'sn' => date("YmdHis") .'-'. mt_rand(1000, 9999),
                    'num' => $goodInfo['num'],
                    'amount' => bcmul($param['number'],$goodInfo['price'],2),
                    'pay_amount' => bcmul($param['number'],$goodInfo['price'],2),
                    'teacher_id' => $user['id'],
                    'pay_type' => $param['pay_type'],
                    'transaction_id' => '',
                    'createtime' => time(),
                    'star_time' => $star_time,
                    'end_time' => $end_time,
                ];
                $orderId = ManystoreOrderRecord::insertGetId($orderInfo);

                //创建主订单记录
                $this->payLogic->createOrder([
                    'shop_id' => $user['shop_id'],
                    'controller' => 'manystore/add_service_order',
                    'out_trade_no' => $orderInfo['sn'],
                    'order_id' => $orderId,
                    'user_id' => $user['id'],
                    'price' => $orderInfo['amount'],
                    'pay_type' => $this->payLogic->payTypeMap()[$param['pay_type']]['code'],
                    'real_price' => $orderInfo['pay_amount'],
                    'pay_amount' => $orderInfo['pay_amount'],
                    'status' => 0,
                    'createtime' => time()
                ]);

                //如果订单价格为0，则直接支付成功
                $payment_json = '';
                $payStatus = 1; //待支付
                if($orderInfo['amount'] == 0){
                    //执行支付成功回调
                    $res = $this->payLogic->payment(
                        [
                            'out_trade_no' => $orderInfo['sn'],
                            'controller' => 'manystore/add_service_order',
                        ]
                    );
                    if($res){
                        $payStatus = 2; //已支付
                    }
                }
                //否则生成回调支付
                else
                {
                    //TODO 根据支付接口生成【后面补上】
                    $payment_json = '';

                    if(!empty($payment_json))
                    {
                        PayLog::where('order_sn', $orderInfo['sn'])->update(['payment_json' => $payment_json]);
                    }
                }

                Db::commit();
                $this->success('创建订单成功','',['order_sn' => $orderInfo['sn'],'pay_status' => $payStatus,'payment_json' => $payment_json]);
            }catch (Exception $e){
                Db::rollback();
                $this->error('创建订单失败');
            }
        }
        else
        {
            $this->error('参数错误');
        }
    }

    /**
     * 提交支付并返回回调信息
     *
     * @ApiMethod (GET)
     * @ApiTitle    提交支付并返回回调信息

     *  @ApiParams (name="order_sn", type="integer", required=false, description="订单编号")

     * @ApiSector   我的接口
     * @ApiReturn   ({
          "code": 1,
          "msg": "获取数据成功",
          "time": "1657984618",
          "data": null
        })
     */
    public function toPay()
    {
        $params = $this->request->param();

        if(empty($params['order_sn']))
        {
            $this->error('请选择要支付的订单');
        }

        $pay_log = PayLog::where('order_sn',$params['order_sn'])->find();
        if(empty($pay_log)){
            $this->error('订单不存在');
        }
        //判断订单类型 各自支付回调
        switch ($pay_log['controller']){
            case 'manystore/add_service_order':
                $this->toPayAddService($params);
                break;
            default:
                break;
        }
    }


    private function toPayAddService($params)
    {
        // 获取订单信息
        $orderInfo = ManystoreOrderRecord::where('sn', $params['order_sn'])->find();

        if($orderInfo['pay_time'] > 0)
        {
            // $this->error('该订单已支付');
        }

        Db::startTrans();
        try {
            

            //如果订单价格为0，则直接支付成功
            $payment_json = '';
            $payStatus = 1; //待支付
            if(true||$orderInfo['amount'] == 0){
                //执行支付成功回调
                $res = $this->payLogic->payment(
                    [
                        'out_trade_no' => $orderInfo['sn'],
                        'controller' => 'manystore/add_service_order',
                    ]
                );
                if($res){
                    $payStatus = 2; //已支付
                }

                $ret_msg = '支付成功';
            }
            //否则生成回调信息
            else
            {
                //TODO 根据支付接口生成【后面补上】
                $payment_json = '';

                if(!empty($payment_json))
                {
                    PayLog::where('order_sn', $orderInfo['sn'])->update(['payment_json' => $payment_json]);
                }

                $ret_msg = '生成支付回调数据成功';
            }

            Db::commit();
            $this->success($ret_msg,'',['order_id' => $orderInfo['id'],'pay_status' => $payStatus,'payment_json' => $payment_json]);
        }catch (Exception $e){
            Db::rollback();
            $this->error('支付失败');
        }
    }
}
